package com.customization.test.demo.util;

import com.alibaba.fastjson.JSONObject;
import weaver.conn.RecordSet;
import weaver.email.EmailWorkRunnable;
import weaver.general.BaseBean;
import weaver.general.StringUtil;
import weaver.general.Util;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;


@Path("/integration/oaAPI")
public class CustomApi {
    private BaseBean lg = new BaseBean();
    private StringBuffer message = new StringBuffer();

    /**
     * 根据建模数据，生成邮件发送给对应的人员
     */
    @POST
    @Path("/doModeExpand/sendEM")
    @Produces(MediaType.APPLICATION_JSON)
    public String doModeExpandSendEM(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        lg.writeLog("==== doModeExpandSendEM start ==== ");
        String dateTime = Util.null2String(request.getParameter("dateTime"));//调用时间
        String billid = Util.null2String(request.getParameter("billid"));//新建或保存的数据id
        String userid = Util.null2String(request.getParameter("userid"));//操作用户id
        String host = Util.null2String(request.getParameter("host"));//访问ip或域名
        String type = Util.null2String(request.getParameter("type"));//接口执行结束后，跳转页面，显示建模显示模板 type = 0
        String modeid = Util.null2String(request.getParameter("modeid"));//表单建模id
        String formid = Util.null2String(request.getParameter("formid"));//表单id ",modeid="+modeid+",formid="+formid
        String uf_tableName = Util.null2String(request.getParameter("uf_tableName"));//建模表
        String uf_tableName_dt1 = Util.null2String(request.getParameter("uf_tableName_dt1"));//建模明细表 uf_lyqk_dt1
        String subjectExtend = Util.null2String(request.getParameter("subjectExtend"));//邮件发送主题扩展内容
        String sendTextExtend = Util.null2String(request.getParameter("sendTextExtend"));//邮件发送正文扩展内容
        lg.writeLog("doModeExpandSendEM 触发时间 dateTime="+dateTime+",billid="+billid
                +",userid="+userid+",host="+host+",type="+type+",modeid="+modeid+",formid="+formid
                +",uf_tableName="+uf_tableName+",uf_tableName_dt1="+uf_tableName_dt1
                +",subjectExtend="+subjectExtend+",sendTextExtend="+sendTextExtend);
        message = new StringBuffer();
        if (!StringUtil.isEmpty(billid)){
            boolean result = false;
            RecordSet rs_getMainHT = new RecordSet();
            RecordSet rs_getDetail = new RecordSet();
            RecordSet rs_getEMail = new RecordSet();
            String sql = "select * from "+uf_tableName+" where id="+billid;
            result = rs_getMainHT.executeQuery(sql);
            if (result && rs_getMainHT.next()){
                //String xhttz = Util.null2String(rs_getMainHT.getString("xhttz"));//合同数据id
                String htqcfwtx = Util.null2String(rs_getMainHT.getString("htqcfwtx"));//合同名称
                String mainid = Util.null2String(rs_getMainHT.getString("id"));//主表数据id
                sql = "select * from "+uf_tableName_dt1+" where mainid="+mainid;
                lg.writeLog("查询当前明细 SQL="+sql);
                result = rs_getDetail.executeQuery(sql);
                if (result){
                    lg.writeLog("获取数据量 "+rs_getDetail.getCounts());
                    while (rs_getDetail.next()){
                        message = new StringBuffer();
                        String mxid = Util.null2String(rs_getDetail.getString("id"));
                        String phry = Util.null2String(rs_getDetail.getString("phry"));
                        String phsx = Util.null2String(rs_getDetail.getString("phsx"));
                        String sfbcyjtzphry = Util.null2String(rs_getDetail.getString("sfbcyjtzphry"));
                        lg.writeLog("mxid="+mxid+",phry="+phry+",phsx="+phsx+",sfbcyjtzphry="+sfbcyjtzphry);

                        if ("0".equals(sfbcyjtzphry)){//若 明细表列字段“是否本次邮件通知配合人员”为是，则推送邮件
                            String subject = "《"+htqcfwtx+"》"+subjectExtend;//邮件主题
                            String sendTo = "";//邮件接收邮箱
                            String email = "";//当前员工邮箱
                            String link = "<a href='"+host+"/spa/cube/index.html#/main/cube/card?type="+type+"&modeId="+modeid+"&formId="+formid+"&billid="+billid+"'>《"+htqcfwtx+"》</a>";
                            //String link = "<a href='"+host+"/spa/cube/index.html#/main/cube/card?type=0&modeId=32501&formId=-332&billid="+billid+"'>《"+htqcfwtx+"》</a>";
                            String sendText = link+" <br/> "+sendTextExtend+phsx;//邮件正文
                            result = rs_getEMail.executeQuery("select email,id from HrmResource where id in (?)",phry);
                            if(result) {
                                while (rs_getEMail.next()){
                                    email = Util.null2String(rs_getEMail.getString(1)) ;
                                    if( !StringUtil.isEmpty(email) && Util.isEmail(email)){
                                        sendTo += email+",";
                                    }
                                }
                            }
                            if (!StringUtil.isEmpty(sendTo)){
                                sendTo = sendTo.substring(0,sendTo.length()-1);
                            }
                            if (!StringUtil.isEmpty(sendTo)){
                                try {
                                    boolean sendMailResult = sendMail(subject,sendTo,sendText);
                                    if (sendMailResult){
                                        result = updateData(uf_tableName_dt1,"sfbcyjtzphry=1","id="+mxid);
                                        if (!result){
                                            message.append("数据状态更新失败!");
                                            lg.writeLog("明细id为"+mxid+"的数据状态更新失败!");
                                        }
                                    }else {
                                        message.append("邮件发送失败!");
                                        lg.writeLog("邮件发送失败!");
                                    }
                                } catch (Exception e) {
                                    message.append("发送邮件报错！提示信息："+e.getMessage());
                                    lg.writeLog("发送邮件报错！提示信息："+e.getMessage());
                                    e.printStackTrace();
                                }
                            }else {
                                message.append("收件人邮箱为空!");
                                lg.writeLog("收件人邮箱为空!");
                            }
                            if (!StringUtil.isEmpty(message.toString())){
                                updateData(uf_tableName_dt1,"yjfsqk='"+message.toString()+"'","id="+mxid);
                            }else {
                                updateData(uf_tableName_dt1,"yjfsqk='成功'","id="+mxid);
                            }
                        }
                    }
                }else {
                    message.append("获取当前建模明细数据失败！<br>");
                    lg.writeLog("获取当前建模明细数据失败！<br> ERROR_SQL="+sql);
                }
            }else {
                message.append("获取当前建模数据失败！<br>");
                lg.writeLog("获取当前建模数据失败！<br> ERROR_SQL="+sql);
            }
        }else {
            message.append("获取当前数据id失败！<br>");
            lg.writeLog("获取当前数据id失败！<br> billid="+billid);
        }

        JSONObject jsonObject_return = new JSONObject();
        if ("".equals(message.toString())){
            jsonObject_return.put("message","1");//message 对应返回结果json对象
        }else {
            jsonObject_return.put("message",message.toString());//message 对应返回结果json对象
        }
        lg.writeLog("==== doModeExpandSendEM == end == 请求结果： "+jsonObject_return.toString());
        return jsonObject_return.toString();
    }

    public boolean updateData(String uf_dzd_tableName,String setData,String condition){
        //无需生成对账文件，更新对应状态字段
        RecordSet rs_update = new RecordSet();
        String sql = "update "+uf_dzd_tableName+" set "+setData+" where "+condition;
        lg.writeLog("更新对应状态字段 SQL="+sql);
        boolean result = rs_update.executeUpdate(sql);
        if (!result){
            lg.writeLog("SQL_ERROR SQL="+sql);
        }
        return result;
    }

    /**
     * 使用OA系统内部邮箱发送邮件
     * @param subject 邮件主题
     * @param sendTo 邮件接收邮箱
     * @param sendText 邮件正文
     * @throws Exception
     */
    public boolean sendMail(String subject,String sendTo,String sendText) {
        lg.writeLog("sendMail start == subject="+subject+",sendTo="+sendTo+",sendText="+sendText);
        //组合邮件内容，发送附件
        EmailWorkRunnable ewr = new EmailWorkRunnable(sendTo, subject, sendText);
        boolean result = ewr.emailCommonRemind(); //result:true投递成功，false投递失败
        lg.writeLog("sendMail end == result="+result);
        return result;
        //eta.sendFormModeMsg(content,userList,para);
    }

}
